#!/usr/bin/env python
# -*- coding: utf-8 -*-
#import wx
import DrawZone
import FrmConfiguracion
import ConexionRobot
import wx.html
import  wx.lib.scrolledpanel as scrolled
import Interprete
import VarGlobales
import os
import time
import Tutorial
import Ayuda

ID_NEW  = 145
ID_OPEN = 146
ID_SAVE = 147
ID_SAVEAS = 148
ID_EXIT = 149

ID_CUT = 150
ID_COPY = 151
ID_PASTE = 152
ID_DEL = 153
ID_SELECTALL = 154 

ID_BTNEXECUTE = 155
ID_BTNSTATE = 156
ID_BTNRESTART = 157



ID_HELP = 162
ID_TUTORIAL = 168
ID_OPTIONS = 164

class FrmPrincipal(wx.Frame):
 
    
    def __init__(self, padre, Titulo):
        super(FrmPrincipal,self).__init__(padre,title=Titulo,size=(1200,650))
        VarGlobales.window=self
        
        # initialized variables
        self.FileOpen = 0 # Has the a file been open, otherwise use saveas
        self.dirname = ''
        self.filename = ''
        self.OldPosTo = -1
        
        self.lblres = None
        #self.modify=0
        
        self.Inicializar() #Crear todos los widgets  
        self.ModoEjecucion = 0
        self.widthpen = "0"
        self.colorfont = (0, 0, 0)
        self.font = self.txt_box.GetFont()
        
        
        self.Eventos()  #eventos
        VarGlobales.canvas = DrawZone.DrawZone(self.Panel_Canvas,self.statusbar)
        VarGlobales.txtconsola = self.lblres
        self.inter = Interprete.Interprete("","")
        
        
        
    def Inicializar(self):
        #Barra de estado 
        self.initStatusBar()
        
        
        #Menu Archivo
        file = wx.Menu()
        file.Append(ID_NEW, '&Nuevo...\tCtrl+N', "Un nuevo archivo")
        file.Append(ID_OPEN, '&Abrir...\tCtrl+A', "Abrir un archivo")
        file.Append(ID_SAVE, '&Guardar...\tCtrl+G', "Guarda el archivo actual")
        file.Append(ID_SAVEAS, 'Guardar como', "Guardar como un nuevo archivo")
        file.Append(ID_EXIT, '&Salir...\tCtrl+S', "Salir")
        
        edit = wx.Menu()
        edit.Append(ID_CUT, 'Cortar\tCtrl+X', "Cortar texto selccionado")
        edit.Append(ID_COPY, 'Copiar\tCtrl+C', "Copiar texto selccionado")
        edit.Append(ID_PASTE, 'Pegar\tCtrl+V', "Pegar informacion")
        edit.Append(ID_SELECTALL, 'Seleccionar todo', "Seleccionar todo el texto")
        edit.Append(ID_DEL, 'Borrar', "Borrar texto selccionado")
        
        #Menu Configurar
        setting = wx.Menu()
        setting.Append(ID_OPTIONS, 'Configurar Entorno', "Opciones de Configuracion")
        
        #Menu Ayuda
        help = wx.Menu()
        help.Append(ID_HELP, 'Ayuda', "Ayuda")
        help.Append(ID_TUTORIAL, 'Tutorial', "Abrir el tutorial")
        
        #Barra de menu
        menubar = wx.MenuBar()
        menubar.Append(file,'Archivo')
        menubar.Append(edit,'Editar')
        menubar.Append(setting,'Configuracion')
        menubar.Append(help,'Ayuda')
        self.SetMenuBar(menubar)
        
        self.lblres = wx.TextCtrl(self, style=wx.TE_MULTILINE, size = (100,100))
        self.lblres.SetEditable(False)
        #contenedor lblres-sizer2
        grid_izq2 = wx.FlexGridSizer(1,2,3,3)
        grid_izq2.AddMany([(self.lblres, 1, wx.EXPAND)])
        grid_izq2.AddGrowableCol(0,1)
        
        
        grid_izq3 = wx.FlexGridSizer(1,2,3,3)
        self.Bntexecute = wx.Button(self,ID_BTNEXECUTE,"Ejecutar")
        self.txtcomandos = wx.TextCtrl(self)
        grid_izq3.AddGrowableCol(0,1)
        
        grid_izq3.AddMany([(self.txtcomandos, 1, wx.EXPAND),(self.Bntexecute,1,wx.EXPAND)])
        self.Panel_Canvas = scrolled.ScrolledPanel(self, -1, size=(900, 400), style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
        ##self.Panel_Canvas.maxWidth  = 5000
        ##self.Panel_Canvas.maxHeight = 5000
        ##self.Panel_Canvas.SetVirtualSize((self.Panel_Canvas.maxWidth, self.Panel_Canvas.maxHeight))
        ##self.Panel_Canvas.SetScrollRate(20,20)
        

        
        #contenedor canvas-grid_izq2-txtcomandos
        grid_izq1 = wx.FlexGridSizer(3,1,3,3)
        grid_izq1.AddMany([(self.Panel_Canvas, 1, wx.EXPAND),(grid_izq2, 1, wx.EXPAND),(grid_izq3, 1, wx.EXPAND)])
        grid_izq1.AddGrowableRow(0,1)
        #self.grid_izq1.AddGrowableRow(2,)
        
        
        
        self.txt_box = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        font1 = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Arial')
        self.txt_box.SetFont(font1)
        
        #contenedor grid_izq1-txt_box
        gridprincipal = wx.FlexGridSizer(2,2,3,3)
        gridprincipal.AddMany([(grid_izq1, 1, wx.EXPAND), (self.txt_box, 1, wx.EXPAND)])
        gridprincipal.AddGrowableRow(0,1)
        gridprincipal.AddGrowableCol(1,1)
        
        #contenedor gridprincipal
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(gridprincipal, 1, wx.EXPAND)
        self.SetSizer(sizer)   
        
        self.PositionUpdate(self) #update the cursor on run
        
        #tutorial
        self.help = wx.html.HtmlHelpController()
        
        self.Maximize()
        self.Show()
        
    def Eventos(self):
        #eventos
        #Archivo
        wx.EVT_MENU(self, ID_NEW, self.OnNew)
        wx.EVT_MENU(self, ID_OPEN, self.OnOpen)
        wx.EVT_MENU(self, ID_SAVE, self.OnSave)
        wx.EVT_MENU(self, ID_SAVEAS, self.OnSaveAs)
        wx.EVT_MENU(self, ID_EXIT, self.OnExit)
        #editar
        wx.EVT_MENU(self, ID_CUT, self.OnCut)
        wx.EVT_MENU(self, ID_COPY, self.OnCopy)
        wx.EVT_MENU(self, ID_PASTE, self.OnPaste)
        wx.EVT_MENU(self, ID_DEL, self.OnDelete)
        wx.EVT_MENU(self, ID_SELECTALL, self.OnSelectAll)
        
        wx.EVT_MENU(self, ID_HELP, self.OnHelp)
        wx.EVT_MENU(self, ID_TUTORIAL, self.OnTutorial)
        wx.EVT_MENU(self, ID_OPTIONS, self.OnOptions)
        
        wx.EVT_BUTTON(self,ID_BTNEXECUTE,self.OnExecute)
        
        wx.EVT_KEY_UP(self.txt_box, self.PositionUpdate)
        wx.EVT_KEY_DOWN(self.txtcomandos,self.onEnterKey)
        wx.EVT_KEY_DOWN(self.Bntexecute,self.onEnterKey)
        #wx.EVT_KEY_UP(self.txt_box, self.Onpress)
        #wx.EVT_LEFT_DOWN(self.txt_box,self.PositionUpdate)
        
    def OnNew(self,event):
        dlg = wx.MessageDialog(self, 'Guardar antes de un nuevo archivo?', '', wx.YES_NO | wx.YES_DEFAULT | 
        wx.CANCEL | wx.ICON_QUESTION)
        val = dlg.ShowModal()
        if val == wx.ID_YES:
            self.OnSave(event)
            self.txt_box.SetValue('')
            self.lblres.SetValue('')
            VarGlobales.canvas.RestartApp()
        elif val == wx.ID_CANCEL:
            dlg.Destroy()
        else:
            dlg.Destroy()
            self.txt_box.SetValue('')
            self.lblres.SetValue('')
            VarGlobales.canvas.RestartApp()
            
        
    def OnOpen(self, event): # Open a file
        """ Open a file """
        dlg = wx.FileDialog(self, "Escoja un archivo", self.dirname, "", "*.*", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname,self.filename),'r')
            self.txt_box.SetValue(f.read())
            self.SetTitle("Editor - " + dlg.GetPath())
            self.FileOpen = 1
            #self.PositionUpdate()
            f.close()
        dlg.Destroy()
        
    def OnSave(self, event): # Save a file 
        """ Save the file to the original file location .... otherwise use saveas """
        if self.FileOpen == 1:
            f = open(os.path.join(self.dirname,self.filename), "w")
            f.write(self.txt_box.GetValue())
            self.SetStatusText("Contenido escrito en " +self.dirname+"\\"+self.filename)
            f.close()
        else:
            self.OnSaveAs(event)
    
    def OnSaveAs(self, event): # Save file to a new path
        """ Save to an arbitrary file and path """
        dlg = wx.FileDialog(self, "Guardar como", self.dirname, self.filename, "Text Files (*.txt)|*.txt|All Files|*.*", wx.SAVE)
        if (dlg.ShowModal() == wx.ID_OK):
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            self.SetTitle("Editor - " + dlg.GetPath())
            self.FileOpen = 1
            self.OnSave(event)
        dlg.Destroy()
        

    def OnExit(self, event):
        #if self.modify:
            dlg = wx.MessageDialog(self, 'Guardar antes de salir?', '', wx.YES_NO | wx.YES_DEFAULT | 
            wx.CANCEL | wx.ICON_QUESTION)
            val = dlg.ShowModal()
            if val == wx.ID_YES:
                self.OnSave(event)
                self.Destroy()
                #if not self.modify:
                #    wx.Exit()
            elif val == wx.ID_CANCEL:
                dlg.Destroy()
            else:
                self.Destroy()
       # else:
        #    self.Destroy()
        
    def OnCut(self, event): # Cut selection
        """ Cuts the selection """
        self.txt_box.Cut()
        #self.PositionUpdate()
    
    def OnCopy(self, event): # Copy Selection
        """ Copies the selection """
        self.txt_box.Copy()
        #self.PositionUpdate()
        
    def OnPaste(self, event): # Paste Selection
        """ Paste the Cut or Copied elements from the clipboard """
        self.txt_box.Paste()
        #self.PositionUpdate()
    
    def OnDelete(self, event): # Delete the selection
        """ Deletes the selected portion """
        fromHere, toHere = self.txt_box.GetSelection()
        self.txt_box.Remove(fromHere, toHere)
    
    def OnSelectAll(self, event): # Select the whole document
        """ Select all the contents of the TextCtrl """
        self.txt_box.SelectAll()
        #self.PositionUpdate()
        
    
    def OnOptions(self, event):
        dlg = FrmConfiguracion.FrmConfiguracion(self, self.font, self.colorfont, self.widthpen, self.ModoEjecucion)
        dlg.ShowModal()
        self.ModoEjecucion = dlg.GetModeExecute()
        if self.ModoEjecucion==1:
            self.SetStatusText("Modo : Programar robot", 1)  #modo
        else:
            self.SetStatusText("Modo : Simulacion", 1)  #modo
        self.widthpen = dlg.GetWidthPen()
        VarGlobales.canvas.SetWidthPen(int(self.widthpen))
        self.font = dlg.GetFont()
        self.colorfont = dlg.GetColorFont()
        self.txt_box.SetFont(self.font)
        self.txt_box.SetForegroundColour(self.colorfont)
        dlg.Destroy()
    
        
    def OnTutorial(self, event):
        frame = wx.Frame(None, -1, "Tutorial", style = wx.DEFAULT_FRAME_STYLE^(wx.MAXIMIZE_BOX |wx.RESIZE_BORDER),size=(1000, 525))
        Tutorial.MyHtmlPanel(frame,-1)
        frame.Show(True)
        
    def OnHelp(self, event):
        frame = wx.Frame(None, -1, "Ayuda", style = wx.DEFAULT_FRAME_STYLE^(wx.MAXIMIZE_BOX |wx.RESIZE_BORDER),size=(1000, 525))
        Ayuda.MyHtmlPanel2(frame,-1)
        frame.Show(True)
        
    
    def onEnterKey(self, event):
        keycode = event.GetKeyCode()
        if keycode == 13:
            self.OnExecute(event)
        elif keycode == 9:
            self.Bntexecute.SetFocus() 
        else:
            event.Skip()
        
    
    def PositionUpdate(self, event): #// Fix this for mouse update as well.
        """ Function to calculate the current position of the cursor and updates the status bar"""
        (posFrom, posTo) = self.txt_box.GetSelection()
        #self.Refresh()
        (col, row) = self.txt_box.PositionToXY(posTo)
        if posFrom == posTo:
            self.SetStatusText(str((row+1, col+1)), 5)
        else:
            delta = posTo - posFrom
            self.SetStatusText(str((row+1, col+1)) + "Sel: " + str(delta), 5)
        self.OldPosTo = posTo
        
            
    def StatusBarShowTime(self): # Update the string on the status bar ... from above it does this once per second
        """ Shows the time in the bottom right status bar column 2 of [0|1|2] """
        t = time.localtime(time.time())
        #if t.tm_sec % 2 == 0:
        ts = time.strftime("%H:%M   %d %b %Y", t) # day, abbrev. month, year, 24h Min
        #else:
        #    ts = time.strftime("%H %M   %d %b %Y", t) # day, abbrev. month, year, 24h Min
        self.SetStatusText(ts, 6) # third position on the status bar
            
    def initStatusBar(self):
        self.statusbar = self.CreateStatusBar()
        self.StatusBar.SetFieldsCount(7)
        self.StatusBar.SetStatusWidths([-2,-2,-2,-2,-2,-1,-2])
        
        self.SetStatusText("Modo : Simulacion", 1)  #modo
        self.SetStatusText("Posicion X: 450.00", 2)      #posX
        self.SetStatusText("Posicion Y: 300.00", 3)      #posY
        self.SetStatusText("Direccion Grados: 0.00", 4)      #Dir
        # Big O - Its show time!  Update the Status bar time once per second
        self.timer = wx.PyTimer(self.StatusBarShowTime)
        #self.timer.Start(1000)
        self.StatusBarShowTime()
        
        
            
    
    def OnExecute(self,event):
        if self.ModoEjecucion == 0:
            txtcode = self.txt_box.GetValue()
            txtinst = self.txtcomandos.GetValue()
            if txtinst != '':
                try:
                    self.inter.Settxtinst(txtinst)
                    self.inter.Execute2()
                    self.lblres.AppendText(txtinst+"\n")
                    self.txtcomandos.SetValue("")
                except Exception as  e1:
                    try:
                        self.inter.Settxtcode(txtcode)
                        self.inter.Settxtinst(txtinst)
                        self.lblres.AppendText(txtinst+"\n")
                        self.inter.Execute()
                        self.txtcomandos.SetValue("")
                    except Exception as  e2:
                        self.lblres.AppendText(str(e2)+"\n")
                        self.txtcomandos.SetValue("")      
        else:
            txtcode = self.txt_box.GetValue()
            txtinst = self.txtcomandos.GetValue()
            if txtinst != '':
                try:
                    self.inter.Settxtcode(txtcode)
                    self.inter.Settxtinst(txtinst)
                    self.lblres.AppendText(txtinst+"\n")
                    self.txtcomandos.SetValue("")
                    codigo = self.inter.GenCodeRobot()
                    print codigo
                    c = ConexionRobot.ConexionRobot()
                    c.Enviar(codigo)
                    c.CerrarConexion()
                except Exception as e2:
                    self.lblres.AppendText(str(e2)+"\n")
                    self.txtcomandos.SetValue("")      
             
                 
           
app = wx.App()
FrmPrincipal(None, Titulo="Editor")
app.MainLoop()
